<template>
    <div class="org-add-container">
        <el-card class="box-card" shadow="hover">
            <!-- 卡片头部 -->
            <div slot="header" class="card-header">
                <span class="header-title">{{ this.form.title }}</span>
            </div>

            <!-- 表单主体 -->
            <el-form ref="form" :model="form" label-width="100px" class="org-form">
                <!-- 第一行：机构编号 + 机构名称 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="医生编号" prop="docterNumber" class="form-item">
                            <el-input v-model="form.docterNumber" disabled class="form-input"
                                placeholder="系统自动生成"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="医生名称" prop="docterName" class="form-item">
                            <el-input v-model="form.docterName" class="form-input" placeholder="请输入医生姓名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别">
                            <el-radio-group v-model="form.docterGender">
                                <el-radio label="男"></el-radio>
                                <el-radio label="女"></el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第二行：机构ID-->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="机构" prop="docterId" class="form-item">
                            <el-select v-model="form.orgId" class="form-select" placeholder="请选择机构"
                                @click.native.prevent="getOrg">
                                <el-option v-if="form.orgName && !orgs.length" :label="form.orgName"
                                    :value="form.orgId" />
                                <el-option v-for="item in orgs" :key="item.orgId" :label="item.orgName"
                                    :value="item.orgId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="团队" prop="docterId" class="form-item">
                            <el-select v-model="form.docterTeamId" class="form-select" placeholder="请选团队（请先选择机构）"
                                @click.native.prevent="getTeams">
                                <el-option v-if="form.docterTeamName && !orgs.length" :label="form.docterTeamName"
                                    :value="form.docterTeamId" />
                                <el-option v-for="item in times" :key="item.docterTeamId" :label="item.docterTeamName"
                                    :value="item.docterTeamId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="医生电话" prop="docterPhone" class="form-item">
                            <el-input v-model="form.docterPhone" class="form-input" placeholder="请输入医生电话"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="医生类型" prop="docterTagId" class="form-item">
                            <el-select v-model="form.docterTagId" class="form-select" placeholder="请选择医生类型"
                                @click.native.prevent="getTags">
                                <el-option v-for="item in tags" :key="item.docterTagId" :label="item.docterTagName"
                                    :value="item.docterTagId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 封面图上传区域 -->
                <el-row :gutter="24" class="form-row upload-row">
                    <el-col :span="24">
                        <el-form-item label="医生头像" class="upload-form-item">
                            <!-- 上传容器：相对定位，用于删除按钮绝对定位 -->
                            <div class="upload-wrapper">
                                <el-upload class="avatar-uploader" :action="serverAddress + 'uploadImg'"
                                    :show-file-list="false" :on-success="handleAvatarSuccess"
                                    :before-upload="beforeAvatarUpload" :disabled="isUploading">
                                    <!-- 图片预览区 -->
                                    <div class="preview-container">
                                        <!-- 已上传图片 -->
                                        <img v-if="form.docterAvator" :src="form.docterAvator" class="avatar-preview"
                                            alt="机构封面图">
                                        <!-- 未上传时的占位 -->
                                        <div v-else class="upload-placeholder">
                                            <i class="el-icon-picture-outline upload-icon"></i>
                                            <p class="upload-text">点击上传封面图</p>
                                        </div>
                                    </div>
                                    <!-- 删除按钮：仅图片存在时显示 -->
                                    <el-button v-if="form.docterAvator" type="text" class="delete-btn"
                                        icon="el-icon-delete" @click.stop="handleImgDelete" :loading="isDeleting">
                                        删除
                                    </el-button>
                                </el-upload>

                                <!-- 上传提示与限制说明 -->
                                <div class="upload-hint">
                                    <span class="hint-text">支持JPG/JPEG格式，大小不超过2MB</span>
                                    <span class="hint-tip" v-if="form.docterAvator">
                                        提示：删除后需重新上传新图片
                                    </span>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第五行：描述 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="24">
                        <el-form-item label="医生擅长" prop="docterGood" class="form-item">
                            <el-input v-model="form.docterGood" class="form-input" type="textarea" rows="3"
                                placeholder="简要描写医生擅长"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" class="form-row">
                    <el-col :span="24">
                        <el-form-item label="医生简介" prop="docterDesc" class="form-item">
                            <el-input v-model="form.docterDesc" class="form-input" type="textarea" rows="3"
                                placeholder="请简要描述简介"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <br></br>
                <!-- 提交按钮 -->
                <el-form-item class="form-submit-row">
                    <el-button type="primary" @click="submitForm(form)" size="medium">
                        提交保存
                    </el-button>
                    <el-button type="default" @click="resetForm('form')" size="medium" style="margin-left: 12px">
                        重置表单
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            tags: [],
            orgs: [],
            times: [],
            serverAddress: this.serveAdd + "imageCtl/",
            form: {
                "docterId": "",
                "docterName": "",
                "docterAvator":"",
                "docterNumber": "",
                "docterPhone": "",
                "docterGender": "",
                "docterTeamId": "",
                "docterTeamName": "",
                "docterTagId":"",
                "docterTagName": "",
                "orgAddress": "",
                "docterDesc":"",
                "orgName": "",
                "orgId":"",
                "orgNumber": 0,
                "orgState": 1,
                "title": "添加医生"
            },
            isUploading: false,  // 上传中状态
            isDeleting: false    // 删除中状态
        };
    },
    created() {
        this.form = this.$route.query;
        console.log(this.form.title);
        console.log(JSON.stringify(this.form))
        //如果是添加机构则搜索
        if(this.form.title === '添加医生'){
            this.getLastDockterNumber();
        }   
    },
    methods: {

        // 获取最新机构编号
        getLastDockterNumber() {
            axios.get('/api/docter/findLastNumber')
                .then(res => {
                    if (res.data && res.data.code === 200) {
                        this.form.docterNumber = res.data.data + 1;
                        console.log(this.form.docterNumber);
                    } else {
                        this.form.docterNumber = Date.now().toString().slice(-6);
                        this.form.orgNumber = Date.now().toString().slice(-6);
                    }
                })
                .catch(error => {
                    console.error('获取医生编号失败：', error);
                    this.$message.error('网络异常，机构医生生成失败');
                    this.form.orgNumber = Date.now().toString().slice(-6);
                });
        },
        getOrg(){
            //获取机构列表
            axios.get('/api/org/findIdAndName')
                .then(res => {
                    if (res.data && res.data.code === 200) {
                        this.orgs = res.data.data;
                        this.form.docterTeamName = "";
                        this.form.docterTeamId = "";
                    } else {
                        this.$message.warning('获取机构列表失败，请重试');
                    }
                })
                .catch(error => {
                    console.error('获取机构列表失败：', error);
                    this.$message.error('网络异常，获取机构列表失败');
                });
        },
        getTeams(){
            //根据机构Id获取团队列表
            axios.get('/api/org/findTeamByOrgId',{params: {orgId: this.form.orgId}})
                .then(res => {
                    if (res.data && res.data.code === 200) {
                        this.times = res.data.data;
                    } else {
                        this.$message.warning('获取团队列表失败，请重试');
                    }
                })
                .catch(error => {
                    console.error('获取团队列表失败：', error);
                    this.$message.error('网络异常，获取团队列表失败');
                });
        },getTags(){
            //获取医生类型列表
            axios.get('/api/docter/findTag')
                .then(res => {
                    if (res.data && res.data.code === 200) {
                        this.tags = res.data.data;
                    } else {
                        this.$message.warning('获取医生类型失败，请重试');
                    }
                })
                .catch(error => {
                    console.error('获取医生类型失败：', error);
                    this.$message.error('网络异常，获取医生类型失败');
                });
        },
        // 图片上传前校验
        beforeAvatarUpload(file) {
            this.isUploading = true;
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传封面图仅支持 JPG/JPEG 格式！');
                this.isUploading = false;
                return false;
            }
            if (!isLt2M) {
                this.$message.error('上传封面图大小不能超过 2MB！');
                this.isUploading = false;
                return false;
            }
            return isJPG && isLt2M;
        },

        // 图片上传成功处理
        handleAvatarSuccess(res, file) {
            this.isUploading = false;
            if (res.code === 500) {
                this.$message({
                    message: res.message || '上传失败',
                    type: "error"
                });
                return;
            }
            if (res.code === 200) {
                this.form.docterAvator = res.data;
                this.$message.success('封面图上传成功！');
            }
        },

        // 图片删除处理
        handleImgDelete() {
            this.$confirm('确定要删除当前封面图吗？删除后需重新上传', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.isDeleting = true;
                axios.delete("api/imageCtl/deleteImg", {
                    params: {
                        imgUrl: this.form.orgAvator
                    }
                }).then(res => {
                    this.isDeleting = false;
                    if (res.data && res.data.code === 200) {
                        this.$message.success('封面图删除成功！');
                        this.form.orgAvator = '';
                    } else {
                        this.$message.warning(res.data?.msg || '删除失败，请重试');
                    }
                }).catch(error => {
                    this.isDeleting = false;
                    console.error('删除图片失败：', error);
                    this.$message.error('网络异常，删除失败');
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },

        // 提交表单
        submitForm(form) {
           if(this.form.title === '添加医生'){
            console.log(JSON.stringify(form));
              axios.post('/api/docter/addDocter', form).then(res => {
                if (res.data && res.data.code === 200) {
                    this.$message.success('机构添加成功！');
                    this.$router.push({ path: '/docterShow' });
                } else {
                    this.$message.warning(res.data?.msg || '机构添加失败，请重试');
                }
            }).catch(error => {
                console.error('机构添加失败：', error);
                this.$message.error('网络异常，机构添加失败');
            });
           }else{
             axios.put('/api/docter/updateDocter', form).then(res => {
                if (res.data && res.data.code === 200) {
                    this.$message.success('机构修改成功！');
                    this.$router.push({ path: '/docterShow' });
                } else {
                    this.$message.warning(res.data?.msg || '机构修改失败，请重试');
                }
            }).catch(error => {
                console.error('机构修改失败：', error);
                this.$message.error('网络异常，机构修改失败');  
           });
           }
        },

        // 重置表单
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.form.orgAvator = '';  // 清空图片
            this.getLastOrgNumber();
        }
    }
};
</script>

<style scoped>
/* 外层容器样式 */
.org-add-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

/* 卡片头部样式 */
.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 20px;
}
.header-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
}

/* 表单整体样式 */
.org-form {
    padding: 20px;
}

/* 表单行样式 */
.form-row {
    margin-bottom: 16px;
}

/* 表单项样式 */
.form-item {
    margin-bottom: 0;
}

/* 输入框和下拉框样式 */
.form-input,
.form-select {
    width: 100%;
    height: 36px;
}
.form-input[type="textarea"] {
    height: auto;
    resize: none;
}

/* 预留列样式 */
.form-empty-col {
    height: 36px;
}

/* 提交按钮行样式 */
.form-submit-row {
    margin-top: 24px;
    text-align: right;
    padding-right: 4px;
}

/* 上传区域样式 */
.upload-row {
    margin-bottom: 20px;
}
.upload-form-item {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    margin-bottom: 0;
}

/* 上传容器样式 */
.upload-wrapper {
    position: relative;
    flex: 1;
}

/* 预览容器样式 */
.preview-container {
    width: 180px;
    height: 135px;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
}

/* 已上传图片样式 */
.avatar-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border: 1px solid #e5e7eb;
}

/* 未上传占位样式 */
.upload-placeholder {
    width: 100%;
    height: 100%;
    background-color: #f9fafb;
    border: 1px dashed #d1d5db;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #6b7280;
}
.upload-icon {
    font-size: 28px;
    margin-bottom: 8px;
}
.upload-text {
    font-size: 14px;
}
.upload-placeholder:hover {
    background-color: #f3f4f6;
    border-color: #409eff;
    color: #409eff;
}

/* 删除按钮样式 */
.delete-btn {
    position: absolute;
    top: -10px;
    right: -10px;
    width: 48px;
    height: 28px;
    background-color: rgba(227, 222, 222, 0.9);
    color:#000000;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    opacity: 0;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.upload-wrapper:hover .delete-btn {
    opacity: 1;
}
.delete-btn:hover {
    background-color: rgba(220, 38, 38, 0.9);
    color: #fff;
}
.delete-btn.is-loading .el-icon-loading {
    font-size: 16px;
}

/* 上传提示文字样式 */
.upload-hint {
    margin-top: 10px;
    font-size: 12px;
    color: #6b7280;
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.hint-tip {
    color: #9ca3af;
}

/* 上传中状态样式 */
.avatar-uploader.is-disabled .preview-container {
    position: relative;
}
.avatar-uploader.is-disabled .preview-container::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.6);
}
.avatar-uploader.is-disabled .preview-container::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 24px;
    height: 24px;
    border: 2px solid #409eff;
    border-top-color: transparent;
    border-radius: 50%;
    animation: loading 1s linear infinite;
}

/* 加载动画 */
@keyframes loading {
    0% { transform: translate(-50%, -50%) rotate(0deg); }
    100% { transform: translate(-50%, -50%) rotate(360deg); }
}

/* 响应式适配 */
@media (max-width: 768px) {
    .org-add-container {
        padding: 10px;
    }
    .form-row .el-col {
        span: 24 !important;
    }
    .form-row {
        margin-bottom: 12px;
    }
    .el-form {
        label-width: 80px !important;
    }
    .preview-container {
        width: 120px;
        height: 90px;
    }
    .upload-icon {
        font-size: 20px;
    }
    .upload-text {
        font-size: 12px;
    }
}
</style>
